//
//  IAPManager.m
//  Paoword
//
//  Created by Wensj on 7/4/16.
//  Copyright © 2016 NME. All rights reserved.
//

#import "IAPManager.h"
#import <IAPHelper.h>
#import <IAPShare.h>
#import <SFHFKeychainUtils.h>
#import "UIDevice+MMGUUID.h"
#import <SVProgressHUD.h>

@implementation IAPManager

+(instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static IAPManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[IAPManager alloc] init];
    });
    return instance;
}

- (void)payWithProduce:(NSString *)iAPId completionBlock:(MMGPaymentCompletion)completionBlock {
    self.completion = completionBlock;
    if (NSStringIsNullOrEmpty(iAPId)) {
        if (completionBlock) {
            MMG_PaymentCallBlock_2(completionBlock, @"商品参数错误", NO);
        }
        return;
    }
    
    [SVProgressHUD show];
    if(![IAPShare sharedHelper].iap) {
        NSSet* dataSet = [[NSSet alloc] initWithObjects:iAPId, nil];
        [IAPShare sharedHelper].iap = [[IAPHelper alloc] initWithProductIdentifiers:dataSet];
        [IAPShare sharedHelper].iap.production = kIAP_PRODUCTION_ENVIROMENT;
        
    }
    
    [IAPShare sharedHelper].iap.productIdentifiers = [[NSSet alloc] initWithObjects:iAPId, nil];
    [[IAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest* request,SKProductsResponse* response) {
        if(response.products.count > 0 ) {
            SKProduct* iapProduct =[[IAPShare sharedHelper].iap.products mg_objectAtIndex:0];
            [[IAPShare sharedHelper].iap buyProduct:iapProduct
                                       onCompletion:^(SKPaymentTransaction* trans){
                                           [SVProgressHUD dismiss];
                                           if(trans.error){
                                               DLog(@"交易失败 %@",[trans.error localizedDescription]);
                                               if (completionBlock) {
                                                   MMG_PaymentCallBlock_2(completionBlock, @"苹果内购交易失败", NO);
                                               }
                                           }else if(trans.transactionState == SKPaymentTransactionStatePurchased) {
                                               
                                               
                                               DLog(@"transaction %@",[[NSString alloc] initWithData:trans.transactionReceipt encoding:NSUTF8StringEncoding]);
                                               
                                               if (completionBlock) {
                                                   MMG_PaymentCallBlock_2(completionBlock, [[NSString alloc] initWithData:trans.transactionReceipt encoding:NSUTF8StringEncoding], YES);
                                               }
//
//                                               [[IAPShare sharedHelper].iap checkReceipt:[NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]] AndSharedSecret:@"your sharesecret" onCompletion:^(NSString *response, NSError *error) {
//                                                   DLog(@"in app purchase response %@ verify url %@",response,[[NSBundle mainBundle] appStoreReceiptURL]);
//                                                   //Convert JSON String to NSDictionary
//                                                   NSDictionary* rec = [IAPShare toJSON:response];
//                                                   if([rec[@"status"] integerValue]==0)  {
//                                                       [[IAPShare sharedHelper].iap provideContentWithTransaction:trans];
//                                                       //同步会员信息到服务器,.......
//                                                       //@"苹果内购交易成功"
//                                                       if (completionBlock) {
//                                                           MMG_PaymentCallBlock_2(completionBlock,[[NSString alloc] initWithData:trans.transactionReceipt encoding:NSUTF8StringEncoding] , YES);
//                                                       }
//                                                       //同步服务器失败后需要的处理
//                                                       /*
//                                                        //同步失败保存member type , 并
//                                                        //在app 退出/进入 时再同步一次到服务器
//                                                        [SFHFKeychainUtils storeUsername:[UIDevice randomUUID] andPassword:iAPId forServiceName:@"IAPHelper" updateExisting:YES error:nil];
//                                                        if (completionBlock) {
//                                                        MMG_PaymentCallBlock_2(completionBlock, @"支付成功，正在处理中", NO);
//                                                        }
//                                                        */
//
//                                                   } else if ([rec[@"status"] integerValue]== 21007) {
//                                                       //21007 收据信息是测试用（sandbox），但却被发送到产品环境中验证
//                                                       [IAPShare sharedHelper].iap.production = NO;
//                                                       [[IAPShare sharedHelper].iap checkReceipt:[NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]] AndSharedSecret:@"your sharesecret" onCompletion:^(NSString *response, NSError *error) {
//                                                           NSDictionary* rec = [IAPShare toJSON:response];
//                                                           if([rec[@"status"] integerValue]==0) {
//                                                               [[IAPShare sharedHelper].iap provideContentWithTransaction:trans];
//                                                               [IAPShare sharedHelper].iap.production = NO;
//
//                                                               //同步会员信息到服务器,.......
//                                                               //@"苹果内购交易成功"
//                                                               if (completionBlock) {
//                                                                   MMG_PaymentCallBlock_2(completionBlock, [[NSString alloc] initWithData:trans.transactionReceipt encoding:NSUTF8StringEncoding], YES);
//                                                               }
//                                                               //同步服务器失败后需要的处理
//                                                               /*
//                                                                //同步失败保存member type , 并
//                                                                //在app 退出/进入 时再同步一次到服务器
//                                                                [SFHFKeychainUtils storeUsername:[UIDevice randomUUID] andPassword:iAPId forServiceName:@"IAPHelper" updateExisting:YES error:nil];
//                                                                if (completionBlock) {
//                                                                MMG_PaymentCallBlock_2(completionBlock, @"支付成功，正在处理中", NO);
//                                                                }
//                                                                */
//
//                                                           } else {
//                                                               [IAPShare sharedHelper].iap.production = kIAP_PRODUCTION_ENVIROMENT;
//                                                               if (completionBlock) {
//                                                                   MMG_PaymentCallBlock_2(completionBlock, @"苹果内购交易失败", NO);
//                                                               }
//
//                                                           }
//                                                       }];
//                                                   } else {
//                                                       if (completionBlock) {
//                                                           MMG_PaymentCallBlock_2(completionBlock, @"苹果内购交易失败", NO);
//                                                       }
//                                                   }
//                                               }];
                                           }
                                           else if(trans.transactionState == SKPaymentTransactionStateFailed) {
                                               if (completionBlock) {
                                                   MMG_PaymentCallBlock_2(completionBlock, @"苹果内购交易失败", NO);
                                               }
                                           }
                                       }];
        }else {
            
            [SVProgressHUD dismiss];
            if (completionBlock) {
                MMG_PaymentCallBlock_2(completionBlock, @"苹果内购交易失败", NO);
            }
        }
    }];
}

+ (void)syncIAPPayInfo {
    //同步上次未同步成功的会员支付信息
//    NSString *memberType = [SFHFKeychainUtils getPasswordForUsername:CURRENTUSER.userId andServiceName:@"IAPHelper" error:nil];
//    if (!NSStringIsNullOrEmpty(memberType)) {
//        [[PWNetAPIManager sharedManager] requestNotifyIAPReuslt:@{@"member_type":@([memberType integerValue])} pathParams:nil andBlock:^(Response *response) {
//            DLog(@"response : %@",response);
//            if (response.code == ResponseCodeSuccess) {
//                [SFHFKeychainUtils deleteItemForUsername:CURRENTUSER.userId andServiceName:@"IAPHelper" error:nil];
//            }else {
//                DLog(@"purchase did failure : status is not equal zero");
//            }
//        }];
//    }
}

@end
